package com.seio.edc.controller.bill;

import com.nova.edc.constant.FileConstant;
import com.nova.edc.model.energy.BillPrintEntity;
import com.nova.edc.model.system.CustomerInfo;
import com.nova.edc.model.system.ModelConstant;
import com.nova.edc.service.energy.BillStatisticsService;
import com.nova.edc.service.energy.GatherSummaryService;
import com.nova.edc.service.energy.OverallStatisticsService;
import com.nova.edc.service.system.CustomerInfoService;
import com.nova.frame.utils.DateUtils;
import com.nova.frame.utils.StringUtils;
import com.seio.edc.controller.BaseAPIController;
import com.seio.edc.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//import com.seio.edc.util.StringUtil;

@Controller
@RequestMapping(value = "/bill")
public class BillContronller extends BaseAPIController {
    private static Logger log = Logger.getLogger(BillContronller.class);
    @Autowired
    private CustomerInfoService novaCustomerInfoService;
    @Autowired
    private BillStatisticsService novaBillStatisticsService;
    @Autowired
    private OverallStatisticsService novaOverallStatisticsService;
    @Autowired
    private GatherSummaryService novaGatherSummaryService;

    @RequestMapping(value = "billList.shtml")
    public ModelAndView billList(HttpServletRequest request, ModelMap modelMap,
                                 Integer companycode, String searchMonth) {
        log.info("账单开始："
                + DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));
        Date startDate;
        Date endDate;
        try {
            CustomerInfo customerInfo = novaCustomerInfoService
                    .getByCompanyCode(companycode);
            modelMap.put("companycode", companycode);
            modelMap.put("customerInfo", customerInfo);

            // 计算日期
            if (StringUtils.isNotNullOrEmpty(searchMonth)) {
                Date date = DateUtil.stringToDate(searchMonth,
                        DateUtil.DEFAULT_DATE_FORMAT_YM);
                startDate = DateUtil.getFirstDayOfMonth(date);
                endDate = DateUtil.getLastDayOfMonth(date);

            } else {
                startDate = DateUtil.getFirstDayOfMonth(DateUtil.getCurDate());
                if (DateUtils.getDay() == 1) {
                    endDate = DateUtil.getCurDate();
                } else {
                    endDate = AssitDateUtil
                            .getAddDay(DateUtil.getCurDate(), -1);
                }
            }

            modelMap.put("monthDateChinese", DateUtil.dateToString(startDate,
                    DateUtil.DEFAULT_DATE_zh_CN_FORMAT_YM));
            modelMap.put("monthDate", DateUtil.dateToString(startDate,
                    DateUtil.DEFAULT_DATE_FORMAT_YM));
            modelMap.put("startDate", DateUtil.dateToString(startDate,
                    DateUtil.DEFAULT_DATE_zh_CN_FORMAT));
            modelMap.put("endDate", DateUtil.dateToString(endDate,
                    DateUtil.DEFAULT_DATE_zh_CN_FORMAT));
            // 最后交费日期
            String lastPayDay = DateUtil.parseDate(
                    DateUtil.toString(AssitDateUtil.getAddMonth(startDate, 1),
                            DateUtil.DEFAULT_DATE_FORMAT_YM)
                            + "-"
                            + customerInfo.getLastpaydate(),
                    DateUtil.DEFAULT_DATE_zh_CN_FORMAT);
            modelMap.put("lastPayDay", lastPayDay);

            // 获取节省的电量和电费
            Map<String, BigDecimal> saveEnergy = novaGatherSummaryService
                    .getStatisticsByDate(customerInfo.getId(), DateUtil.dateToString(
                                    startDate, DateUtil.DEFAULT_DATE_FORMAT),
                            DateUtil.dateToString(endDate,
                                    DateUtil.DEFAULT_DATE_FORMAT));
            BigDecimal saveCost = saveEnergy.get(ModelConstant.SAVE_COST)
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal copeproportion = new BigDecimal(0);
            if (customerInfo.getCopeproportion() != null) {
                copeproportion = customerInfo.getCopeproportion();
            }
            BigDecimal payCost = saveCost
                    .multiply(copeproportion)
                    .divide(new BigDecimal(100))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal conventionprice = new BigDecimal(0);
            if (customerInfo.getConventionprice() != null) {
                conventionprice = customerInfo.getConventionprice();
            }
            BigDecimal maintenanceprice = new BigDecimal(0);
            if (customerInfo.getMaintenanceprice() != null) {
                maintenanceprice = customerInfo.getMaintenanceprice();
            }
            String conventionpriceCN = MoneyUtil.toChinese(conventionprice.toString());
            String maintenancepriceCN = MoneyUtil.toChinese(maintenanceprice.toString());
            BigDecimal multipleCost = payCost.add(
                    conventionprice).add(
                    maintenanceprice);
            String multipleCostCN = MoneyUtil
                    .toChinese(multipleCost.toString());

            modelMap.put("conventionpriceCN", conventionpriceCN);
            modelMap.put("maintenancepriceCN", maintenancepriceCN);
            modelMap.put("payCost", payCost);
            modelMap.put("multipleCost", multipleCost);
            modelMap.put("multipleCostCN", multipleCostCN);
            modelMap.put("saveEnergy", saveEnergy);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return new ModelAndView("bill/billList", modelMap);

    }

    @RequestMapping(value = "billPrint.shtml")
    @ResponseBody
    public Map<String, Object> billPrint(HttpServletRequest request,
                                         @RequestBody BillPrintEntity billPrintEntity) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String filePath = this.exportPDF(billPrintEntity, request);
            map.put("filename", filePath);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("filename", "error");
        }
        return map;
    }

    private String exportPDF(BillPrintEntity billPrintEntity,
                             HttpServletRequest request) throws Exception {
        // 导出pdf路径
        String templateDir = request.getSession().getServletContext()
                .getRealPath("");
        String tempDir = templateDir + "/temp/";
        File file = new File(tempDir);
        if (!file.exists()) {
            file.mkdir();
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
        String dateStr = format.format(new Date());
        String fileName = "BillReport" + dateStr + ".pdf";
        String filename = tempDir + fileName;

        // 资源路径
        String reportSoursePath = templateDir + "/src/common/ledBill.jrxml";
        ArrayList<BillPrintEntity> data = new ArrayList<BillPrintEntity>();
        data.add(billPrintEntity);
        // // 打印
        // JRDataSource dataSource = new JRBeanCollectionDataSource(data);
        // JasperDesign design = JRXmlLoader.load(reportSoursePath);
        // JasperReport report = JasperCompileManager.compileReport(design);
        // JasperPrint print = JasperFillManager.fillReport(report, null,
        // dataSource);
        // JasperExportManager.exportReportToPdfFile(print, filename);
        return "temp/" + fileName;
        // return
        // "D:\\tomcat-7.0.27-aizhufu\\webapps\\led2\\temp\\BillReport20140928061000.pdf";
    }

    @RequestMapping(value = "pagePrint.shtml")
    public ModelAndView pagePrint(HttpServletRequest request, ModelMap modelMap) {
        String filename = request.getParameter("filename");
        modelMap.put("filename", filename);
        return new ModelAndView("bill/billPrintpage", modelMap);
    }

    @RequestMapping(value = "printPreview.shtml")
    public ModelAndView printPreview(HttpServletRequest request,
                                     BillPrintEntity billPrintEntity, ModelMap modelMap) {
        modelMap.put("billPrintEntity", billPrintEntity);
        return new ModelAndView("bill/billPreview", modelMap);
    }

    @RequestMapping(value = "toPrint.shtml")
    @ResponseBody
    public Map<String, Object> toPrint(HttpServletRequest request, String html,
                                       String title, ModelMap modelMap) {
        Map<String, Object> map = new HashMap<String, Object>();
        String path = FileUtil.getPath(FileConstant.BILL_DIR,
                FileConstant.TYPE_PDF_DIR);

        String filePath = FileUtil.getDir(request.getSession()
                .getServletContext().getRealPath(""), path)
                + File.separator + title + ".pdf";
        try {
            String content = URLDecoder.decode(html, "UTF-8");
            PdfUtil.generatePdfByHtml(content, filePath);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        map.put("path", path + File.separator + title + ".pdf");
        return map;
    }
}
